#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/9 22:32
# @Author : cjw
from typing import Optional

from fastapi import APIRouter, BackgroundTasks, Depends

app08 = APIRouter()

"""【见run.py】Middleware 中间件"""
# 注意：带yield的依赖的退出部分代码和后台任务，会在中间件之后运行

"""【见run.py】跨域资源共享"""
# 域的概念：协议+域名+端口

"""后台任务"""


def bg_task(framework: str):
	with open('bg_task.txt', 'a', encoding='utf-8') as f:
		f.write(framework)


@app08.post('/background_tasks', summary='后台任务')
async def background_tasks(framework: str, bts: BackgroundTasks):
	"""
	后台任务
	:param framework: 被调用的后台任务函数参数
	:param bts: FastAPI.BackgroundTasks
	:return:
	"""
	bts.add_task(bg_task, framework)
	return {'message': '任务已在后台运行'}


def continue_write_content(bts: BackgroundTasks, q: Optional[str] = None):
	if q:
		bts.add_task(bg_task, '任务已在后台运行')
	return q


@app08.post('/dependency/background_tasks', summary='依赖注入后台任务')
async def dependency_background_tasks(q: str = Depends(continue_write_content)):
	if q:
		return {'message': '任务已在后台运行'}
